﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using SharePoint.Contrib.Extensions;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace NUnit.SharePointContrib
{
    [TestFixture]
    public class SPWebExtensionsTest
    {

        SPSite sitecollection = null;
        SPWeb root = null;
        Guid listID = Guid.Empty;
        const string ListName = "SPWebExtensionsTest";

        [SetUp]
        public void Init()
        {
            if (SharePoint.TryFindSiteCollection(out sitecollection))
            {
                root = sitecollection.RootWeb;
                listID = root.Lists.Add(ListName, "", SPListTemplateType.GenericList);
            }
        }

        [TearDown]
        public void Dispose()
        {
            root.Properties.Remove(ListName);
            root.Properties.Update();
            root.Lists[listID].Delete();
            root.Update();
            sitecollection.Dispose();
        }


        [Test]
        public void TryFindListByNameIsCached()
        {
            SPList list = null;
            Stopwatch sw = new Stopwatch();

            sw.Start();
            Assert.True(root.TryFindListByName(ListName, out list));
            sw.Stop();
            var first = sw.Elapsed;

            Assert.True(root.Properties.ContainsKey(ListName));
            Assert.NotNull(list);

            sw.Reset();

            sw.Start();
            Assert.True(root.TryFindListByName(ListName, out list));
            sw.Stop();

            var second = sw.Elapsed;

            Assert.That(first, Is.GreaterThan(second));
        }


        [Test]
        public void TryFindListByNameCanFail()
        {
            SPList list = null;
            Assert.False(root.TryFindListByName("notfound", out list));
        }
        
        [Test]
        public void ContentTypeCanBeFound()
        {
            SPContentType masterpage;

            Assert.True(root.TryFindContentType(SPBuiltInContentTypeId.MasterPage, out masterpage));
            Assert.NotNull(masterpage);
            Assert.That(masterpage.Id, Is.EqualTo(SPBuiltInContentTypeId.MasterPage));
        }

        [Test]
        public void RunWithUnsafeUpdatesIsUnsafeAndCanSetOldValueBackAfter()
        {
            SharePoint.SPWebAccessor(web =>
                {
                    bool before = web.AllowUnsafeUpdates;
                    
                    web.RunWithUnsafeUpdates(web2 =>
                        {
                            Assert.That(web2.AllowUnsafeUpdates, Is.True);
                        });

                    Assert.That(web.AllowUnsafeUpdates, Is.EqualTo(before));

                });
        }
    }
}
